<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" v-model="listQuery" class="search">
        <el-form-item label="">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入项目名称/单位名称"
            clearable
            size="small"
            @keyup.enter.native="handleFilter"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            size="small"
            v-model="listQuery.search_date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="datas"
        border
        v-loading="listLoading"
        fit
        highlight-current-row
        style="width: 100%"
        size="small"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column type="expand" label="#" align="center">
          <template slot-scope="scope">
            <el-table :data="scope.row.details" border size="small">
              <el-table-column
                label="工程款类别"
                prop="fund_class_name"
                align="center"
              ></el-table-column>
              <el-table-column
                label="支付时间"
                prop="fund_date"
                align="center"
              ></el-table-column>
              <el-table-column
                label="金额(元)"
                prop="money"
                align="center"
                :formatter="dataFormatter"
              ></el-table-column>
              <el-table-column
                label="备注"
                prop="remark"
                align="center"
              ></el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :align="column.align"
          :width="column.width ? column.width : ''"
          :formatter="dataFormatter"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getFinanceList"
      />
    </el-card>
    <!-- 对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="getTitle"
      width="50%"
      top="10px"
    >
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        size="small"
        label-position="right"
        style="width: 95%; padding: 0 30px"
        status-icon
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="project">
              <el-select
                v-model="form.project"
                placeholder="项目名称"
                filterable
                clearable
                @change="onChange"
              >
                <el-option
                  v-for="item in projects"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位名称" prop="company">
              <el-input
                v-model="form.company"
                placeholder="单位名称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同金额" prop="contract_accounts">
              <el-input
                v-model="form.contract_accounts"
                placeholder="合同金额"
                clearable
              >
                <template slot="append">
                  <el-button type="default">元</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="往年发票金额" prop="former_bill">
              <el-input
                v-model="form.former_bill"
                placeholder="往年开发票金额"
                clearable
              >
                <template slot="append">
                  <el-button type="default">元</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本年发票金额" prop="current_bill">
              <el-input
                v-model="form.current_bill"
                placeholder="本年开发票金额"
                clearable
              >
                <template slot="append">
                  <el-button type="default">元</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目经理" prop="manager">
              <el-input
                v-model="form.manager"
                placeholder="项目经理"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="telephone">
              <el-input
                v-model="form.telephone"
                placeholder="联系方式"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row> </el-row>
        <el-tabs v-model="activeName" stretch>
          <el-tab-pane label="已收甲方工程款(含预付)" name="0">
            <el-table :data="form.recv_funds" border size="mini" width="100%">
              <el-table-column
                type="index"
                label="序号"
                align="center"
              ></el-table-column>
              <el-table-column label="时间" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0"
                    :prop="'recv_funds.' + scope.$index + '.fund_date'"
                    :rules="formRules.fund_date"
                  >
                    <el-date-picker
                      size="mini"
                      v-model="scope.row.fund_date"
                      placeholder="选择时间"
                      value-format="yyyy-MM-dd"
                    >
                    </el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="金额(元)" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0"
                    :prop="'recv_funds.' + scope.$index + '.money'"
                    :rules="formRules.money"
                  >
                    <el-input
                      v-model="scope.row.money"
                      placeholder="金额"
                      size="mini"
                      clearable
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0"
                    :prop="'recv_funds.' + scope.$index + '.remark'"
                  >
                    <el-input
                      v-model="scope.row.remark"
                      placeholder="备注"
                      size="mini"
                      clearable
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80px" align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0">
                    <el-button
                      type="danger"
                      size="mini"
                      circle
                      icon="el-icon-delete"
                      @click="handleItemDelete(scope)"
                    ></el-button>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="已付项目部工程款" name="1">
            <el-table :data="form.pay_funds" border size="mini" width="100%">
              <el-table-column
                type="index"
                label="序号"
                align="center"
              ></el-table-column>
              <el-table-column label="时间" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0"
                    :prop="'pay_funds.' + scope.$index + '.fund_date'"
                    :rules="formRules.fund_date"
                  >
                    <el-date-picker
                      size="mini"
                      v-model="scope.row.fund_date"
                      placeholder="选择时间"
                      value-format="yyyy-MM-dd"
                    >
                    </el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="金额(元)" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0"
                    :prop="'pay_funds.' + scope.$index + '.money'"
                    :rules="formRules.money"
                  >
                    <el-input
                      v-model="scope.row.money"
                      placeholder="金额"
                      size="mini"
                      clearable
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0"
                    :prop="'pay_funds.' + scope.$index + '.remark'"
                  >
                    <el-input
                      v-model="scope.row.remark"
                      placeholder="备注"
                      size="mini"
                      clearable
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80px" align="center">
                <template slot-scope="scope">
                  <el-form-item label-width="0">
                    <el-button
                      type="danger"
                      size="mini"
                      circle
                      icon="el-icon-delete"
                      @click="handleItemDelete(scope)"
                    ></el-button>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer">
        <span style="margin-right: 40px">
          <el-button type="default" @click="dialogVisible = false" size="mini"
            >返回</el-button
          >
        </span>

        <el-button
          type="success"
          size="mini"
          icon="el-icon-plus"
          @click="handleItemAdd"
          >新增行</el-button
        >
        <el-button type="primary" @click="handleSave(false)" size="mini"
          >保存</el-button
        >
        <el-button type="primary" size="mini" @click="handleSave(true)"
          >保存并新增</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  getPrjectFinances,
  addProjectFinance,
  updateProjectFinance,
  delProjectFinance,
  delFundsDetail,
  getProjectList,
} from "@/api/building";

import { getParentsPath } from "@/utils/index";
import Pagination from "@/components/Pagination";
import { toThousandFilter } from "@/filters";

const defaultForm = {
  id: null,
  project: null,
  company: null,
  contract_accounts: 0,
  former_bill: 0,
  current_bill: 0,
  remark: "",
  manager: "",
  telephone: "",
  user: null,
  details: [],
  recv_funds: [],
  pay_funds: [],
};
const defDetailForm = {
  id: undefined,
  fund_class: 0,
  fund_date: null,
  remark: null,
  money: 0,
};

export default {
  name: "Finance",
  data() {
    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        project: [
          {
            required: true,
            message: "请选择项目",
            trigger: ["blur", "change"],
          },
        ],
        company: [
          {
            required: true,
            message: "请输入公司名称",
            trigger: ["blur"],
          },
        ],
        fund_date: [
          {
            required: true,
            message: "选择时间",
            trigger: ["blur", "change"],
          },
        ],
        money: [
          {
            required: true,
            message: "输入金额",
            trigger: ["blur", "change"],
          },
        ],
      },
      tableColumns: [
        {
          key: "project_name",
          title: "项目名称",
          align: "left",
          width: "200px",
        },
        {
          key: "company",
          title: "单位名称",
          align: "center",
        },
        {
          key: "contract_accounts",
          title: "合同金额(元)",
          align: "center",
          width: "120px",
        },
        // {
        //   key: "balance_accounts",
        //   title: "完工结算金额(元)",
        //   align: "center",
        //   width: "120px",
        // },
        // {
        //   key: "bill_name",
        //   title: "发票",
        //   align: "center",
        // },
        // {
        //   key: "checkout_name",
        //   title: "结账",
        //   align: "center",
        // },
        {
          key: "receive_money",
          title: "已收甲方工程款(元)",
          align: "center",
          width: "120px",
        },
        {
          key: "pay_money",
          title: "已付工程部工程款(元)",
          align: "center",
          width: "120px",
        },
        {
          key: "remain_money",
          title: "剩余工程款(元)",
          align: "center",
          width: "120px",
        },
        {
          key: "former_bill",
          title: "往年发票金额(元)",
          align: "center",
        },
        {
          key: "current_bill",
          title: "本年发票金额(元)",
          align: "center",
        },
        // {
        //   key: "manager",
        //   title: "项目经理",
        //   align: "left",
        // },
        // {
        //   key: "telephone",
        //   title: "联系方式",
        //   align: "left",
        // },
        // {
        //   key: "remark",
        //   title: "备注",
        //   align: "left",
        // },
      ],
      title: "项目综合统计",
      dialogVisible: false,
      datas: [],
      projects: [],

      dialogType: "new",
      activeName: "0",
      total: 0,
      listLoading: true,
      flags: [
        { id: 1, name: "是" },
        { id: 0, name: "否" },
      ],
      listQuery: {
        page: 1,
        page_size: 20,
        name: null,
        // search_date: null,
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["uid", "is_super"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getFinanceList();
    this.getAllProject();
  },
  methods: {
    getFinanceList() {
      this.listLoading = true;
      getPrjectFinances(this.listQuery)
        .then((res) => {
          const datas = res.results.map((item) => {
            item["remain_money"] = item.receive_money - item.pay_money;
            return item;
          });
          this.datas = res.results;
          this.listLoading = false;
          this.total = res.count;
        })
        .catch((error) => {
          this.$message.error("获取数据失败!");
          this.listLoading = false;
        });
    },
    getAllProject() {
      getProjectList()
        .then((res) => {
          this.projects = res;
        })
        .catch((error) => {
          this.$message.error("获取工程列表失败!");
        });
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getFinanceList();
    },
    // 增加
    handleAdd() {
      // defaultForm.details = [];
      // defaultForm.recv_funds = [];
      // defaultForm.pay_funds = [];
      this.activeName = "0";
      this.form = Object.assign({}, defaultForm);

      this.form.details = [];
      this.form.recv_funds = [];
      this.form.pay_funds = [];

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    //增加行
    handleItemAdd() {
      defDetailForm.fund_class = +this.activeName;
      if (this.activeName === "0") {
        this.form.recv_funds.push(Object.assign({}, defDetailForm));
      } else {
        this.form.pay_funds.push(Object.assign({}, defDetailForm));
      }
    },
    // 修改
    handleEdit(scope) {
      this.form = scope.row;
      this.dialogType = "edit";
      this.activeName = "0";
      this.form.recv_funds = this.form.details.filter(
        (item) => item.fund_class === 0
      );
      this.form.pay_funds = this.form.details.filter(
        (item) => item.fund_class === 1
      );
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除这条记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delProjectFinance(row.id);
          this.datas.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //删除行
    handleItemDelete(scope) {
      console.log(scope);
      let row = scope.row;

      if (row.id == undefined || row.id == null) {
        if (this.activeName === "0") {
          this.form.recv_funds.splice(scope.$index, 1);
        } else {
          this.form.pay_funds.splice(scope.$index, 1);
        }
      } else if (row.id > 0) {
        this.$confirm("确定要删除吗?", "删除提示：", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            try {
              const res = await delFundsDetail(row.id);
              // this.form.details.splice(scope.$index, 1);
              if (this.activeName === "0") {
                this.form.recv_funds.splice(scope.$index, 1);
              } else {
                this.form.pay_funds.splice(scope.$index, 1);
              }
              this.form.details = this.form.recv_funds.concat(
                this.form.pay_funds
              );
              this.$message({ type: "success", message: "删除成功!" });
            } catch (err) {
              this.$message.error("删除失败!");
            }
          })
          .catch((error) => {});
      }
    },
    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          if (this.form.user == null) {
            this.form.user = this.uid;
          }
          this.form.details = this.form.recv_funds.concat(this.form.pay_funds);
          delete this.form.pay_funds;
          delete this.form.recv_funds;
          res = await updateProjectFinance(this.form);
        } else {
          this.form.user = this.uid;
          this.form.details = this.form.recv_funds.concat(this.form.pay_funds);
          delete this.form.pay_funds;
          delete this.form.recv_funds;
          res = await addProjectFinance(this.form);
        }

        this.getFinanceList();

        const { project_name, company } = res;
        if (flag) {
          this.form = Object.assign({}, defaultForm);
          this.form.details = [];
          this.form.recv_funds = [];
          this.form.pay_funds = [];
          this.dialogType = "new";

          this.$nextTick(() => {
            this.$refs.formRef.clearValidate();
          });
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>项目名称: ${project_name}</div>
              <div>单位名称: ${company}</div>
            `,
          type: "success",
        });
      });
    },
    onChange(value) {
      console.log(value);
      const index = this.projects.findIndex((v) => v.id == value);
      const item = this.projects[index];
      this.form.project = item.id;
      this.form.contract_accounts = item.archive.costs;
      this.form.manager = item.archive.duty_man;
    },
    //格式化
    dataFormatter(row, column, cellValue, index) {
      if (
        column.property == "contract_accounts" ||
        column.property == "balance_accounts" ||
        column.property == "former_bill" ||
        column.property == "current_bill" ||
        column.property == "receive_money" ||
        column.property == "pay_money" ||
        column.property == "money" ||
        column.property == "remain_money"
      ) {
        return cellValue && toThousandFilter(cellValue.toFixed(2));
      } else {
        return cellValue;
      }
    },

    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "合计";
          return;
        }
        if (
          column.property == "contract_accounts" ||
          column.property == "balance_accounts" ||
          column.property == "former_bill" ||
          column.property == "current_bill" ||
          column.property == "receive_money" ||
          column.property == "pay_money" ||
          column.property == "money" ||
          column.property == "remain_money"
        ) {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] = toThousandFilter(sums[index]);
          sums[index] += " 元";
        } else {
          return;
        }
      });

      return sums;
    },
  },
};
</script>

<style lang='scss' scoped>
</style>